package com.cx.config;


import com.cx.config.properties.DataSourceMapProperties;
import com.cx.config.properties.DomainMappingProperties;
import com.cx.sources.DynamicTenantDataSources;
import com.mysql.cj.jdbc.MysqlDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.*;


/**
 * @auth dijia
 * @date 2023/5/26 16:04
 */
@Configuration
@Slf4j
public class DataSourceConfig {

    @Autowired
    private DataSourceMapProperties dataSourceMapProperties;

    @Autowired
    private DomainMappingProperties domainMappingProperties;

    @Bean
    @Primary
    public DataSource dataSource() {
        DynamicTenantDataSources dataSource = new DynamicTenantDataSources();
        //添加多数据源
        Map<Object, Object> map = new HashMap<>();
        //添加默认数据源
        MysqlDataSource defaultData = new MysqlDataSource();
        dataSourceMapProperties.getMap().forEach(c -> {
            if (Objects.nonNull(c.getTenantId())) {
                MysqlDataSource mysqlDataSource = new MysqlDataSource();
                mysqlDataSource.setURL(DynamicTenantDataSources.urlWrapper(c.getUrl()));
                mysqlDataSource.setUser(c.getUsername());
                mysqlDataSource.setPassword(c.getPassword());
                map.put(DynamicTenantDataSources.nameWrapper(c.getTenantId()), mysqlDataSource);
            } else {
                defaultData.setURL(c.getUrl());
                defaultData.setUser(c.getUsername());
                defaultData.setPassword(c.getPassword());
            }
        });
        dataSource.setTargetDataSources(map);

        dataSource.setDefaultTargetDataSource(defaultData);

        dataSource.afterPropertiesSet();
        return dataSource;
    }
}
